package com.mamesoft.medicipazienti.servlet;

import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class RichiamaServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static Logger log = Logger.getLogger(RichiamaServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection connect = null;
        PrintWriter out = null;
        try {
            PropertyConfigurator.configure(RichiamaServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));
            response.setContentType("text/html;charset=UTF-8");
            HttpSession session = request.getSession();

            connect = JDBC.connect();

            out = response.getWriter();

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"/MediciPazienti/variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");
            out.println("    </head>");

            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"/MediciPazienti/logout\">Logout</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");

            out.println("            <div id=\"sidebar\">");
            out.println("               <ul class = \"sidemenu\">");
            out.println("                   <li><a href=\"/MediciPazienti/medico/welcome\">Home</a><li>");
            out.println("                   <li><a class=\"active\" href=\"/MediciPazienti/medico/richiama\">Invia richiami</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/medico/visualizza_storico\">Visualizza Storico</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/logout\">Logout</a><li>");
            out.println("               </ul>");
            out.println("            </div>");

            out.println("            <div id =\"content\">");
            out.println("                <div id=\"feature\">");
            out.println("                    <p>" + session.getAttribute("last_login") + "</p>");
            out.println("</p>");
            out.println("                </div>");
            out.println("                <div class=\"post\">");

            Timestamp tS;
            DateFormat c = DateFormat.getDateTimeInstance();
            if (request.getParameter("seconds") != null) {
                int seconds = 0;
                try {
                    seconds = Integer.parseInt(request.getParameter("seconds"));
                    if (seconds >= 0) {
                        tS = new Timestamp(System.currentTimeMillis() - (seconds * 1000));
                        out.println("<h2>Vaccini effettuati prima del " + c.format(tS) + "</h2>");
                    } else {
                        tS = new Timestamp(System.currentTimeMillis());
                        out.println("<h2>Vaccini effettuati prima del " + c.format(tS) + "</h2>");
                    }
                } catch (NumberFormatException e) {
                    out.println("<h2>Invia richiami</h2>");
                }
            } else {
                out.println("<h2>Invia richiami</h2>");
            }


            out.println("<p>Inserisci un numero: cliccando su \"Invia\" visualizzerai i pazienti che si sono vaccinati prima di tale arco partendo da ora "
                    + "(Il numero deve essere espresso in secondi)</p>");
            out.println("<form action=\"richiama\" method=\"POST\">");
            out.println("                    <input type=\"text\" name=\"seconds\" value=\"\" />");
            out.println("                    <input type=\"submit\" value=\"Invia\" /><br><br>");
            out.println("</form>");

            Boolean isOk = true;
            if (request.getParameter("seconds") != null) {
                int seconds = 0;
                try {
                    seconds = Integer.parseInt(request.getParameter("seconds"));
                } catch (NumberFormatException e) {
                    out.println("<p>Devi inserire un numero espresso in secondi, riprova!</p>");
                    isOk = false;
                }
                if (seconds < 0) {
                    seconds = 0;
                    out.println("<p>Hai inserito un valore negativo, visualizzati tutti i vaccini</p>");
                }
                if (isOk) {
                    Timestamp t = new Timestamp(System.currentTimeMillis() - (seconds * 1000));
                    String query = "Select * FROM("
                            + "SELECT paziente.ID AS ID, paziente.nome AS Nome,paziente.cognome AS Cognome, "
                            + "paziente.foto AS Foto, MAX(vaccino.data) AS Data "
                            + "FROM paziente JOIN vaccino ON (ID = pID) "
                            + "GROUP BY ID) AS t "
                            + "WHERE t.Data < '" + t.toString() + "' "
                            + "ORDER BY t.Data DESC";
                    ResultSet set = null;
                    ArrayList<String> nome = new ArrayList<String>();
                    ArrayList<String> cognome = new ArrayList<String>();
                    ArrayList<String> data = new ArrayList<String>();
                    ArrayList<String> urlFoto = new ArrayList<String>();
                    ArrayList<Integer> pID = new ArrayList<Integer>();

                    set = JDBC.executeQuery(query, connect);
                    try {
                        while (set.next()) {
                            pID.add(set.getInt("ID"));
                            nome.add(set.getString("Nome"));
                            cognome.add(set.getString("Cognome"));
                            data.add(c.format(set.getTimestamp("Data")));
                            urlFoto.add(set.getString("Foto"));
                        }
                    } catch (SQLException ex) {
                        out.println("Nessun risultato trovato.");
                    }

                    set.close();

                    out.println("<form action=\"conferma_richiami\" method=\"POST\">");
                    out.println("<table width=\"700\">");
                    if (!pID.isEmpty()) {

                        out.println("<thead>");
                        out.println("   <tr>");
                        out.println("       <th>SELEZIONA</th>");
                        out.println("       <th>Foto</th>");
                        out.println("       <th>Paziente</th>");
                        out.println("       <th>Data ultimo vaccino</th>");
                        out.println("   </tr>");
                        out.println("</thead>");
                        out.println("<tbody>");
                        for (int i = 0; i < pID.size(); i++) {
                            out.println("   <tr>");
                            out.println("       <td align=\"center\"><input type=\"checkbox\" name=\"" + pID.get(i) + "\" value=\"u\" /></td>");
                            out.println("       <td><IMG SRC=\"/MediciPazienti" + urlFoto.get(i).replace("jpg", "JPG") + "\" WIDTH=\"50\" HEIGHT=\"50\"></td>");
                            out.println("       <td>" + nome.get(i) + " " + cognome.get(i) + "</td>");
                            out.println("       <td>" + data.get(i) + "</td>");
                            out.println("   </tr>");
                        }
                        out.println("</tbody>");
                        out.println("</table>");
                    }
                    query = "SELECT * FROM paziente WHERE ID != ALL ("
                            + "SELECT DISTINCT pID FROM vaccino)";

                    set = JDBC.executeQuery(query, connect);

                    out.println("<p><br>Questi pazienti non si sono mai sottoposti a vaccino:</p>");
                    out.println("<table width=\"450\">");
                    out.println("<thead>");
                    out.println("   <tr>");
                    out.println("       <th>SELEZIONA</th>");
                    out.println("       <th>Foto</th>");
                    out.println("       <th>Paziente</th>");
                    out.println("   </tr>");
                    out.println("</thead>");
                    out.println("<tbody>");


                    set.next();
                    if (set.getString("Foto") != null) {
                        do {
                            out.println("   <tr>");
                            out.println("       <td align=\"center\"><input type=\"checkbox\" name=\"" + set.getInt("ID") + "\" value=\"s\" /></td>");
                            out.println("       <td><IMG SRC=\"/MediciPazienti/" + set.getString("Foto").replace("jpg", "JPG") + "\" WIDTH=\"50\" HEIGHT=\"50\"></td>");
                            out.println("       <td>" + set.getString("Nome") + " " + set.getString("Cognome") + "</td>");
                            out.println("   </tr>");
                        } while (set.next());
                    }


                    out.println("</tbody>");
                    out.println("</table>");
                    out.println("<input type=\"submit\" value=\"Procedi\" />");
                    out.println("</form>");

                }
            }


            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");

        } catch (Exception ex) {
            request.getSession().invalidate();
            if (ex instanceof SQLException) {
                log.error("SQL Exception");
                response.sendRedirect("/MediciPazienti/database_error.html");
            } else {
                log.error(ex.toString());
                response.sendRedirect("/MediciPazienti/general_error.html");
            }
        } finally {
            if (connect != null) {
                try {
                    connect.close();
                } catch (SQLException ex) {
                    request.getSession().invalidate();
                    log.error("SQL Exception");
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
            if (out != null) {
                out.close();
            }
        }
    }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
